package com.sticktogether.multiphotoselect;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.sticktogether.R;
import com.sticktogether.photoreceiver.PhotoDatabase;
import com.sticktogether.photoreceiver.WifiChangeBroadcastReceiver;
import com.sticktogether.server.ServerCommunication;
import com.sticktogether.services.UploadService;


/**
 * @author Paresh Mayani (@pareshmayani)
 */
public class MultiPhotoSelectActivity extends Activity {

	private ArrayList<String> imageUrls;
	private DisplayImageOptions options;
	private ImageAdapter imageAdapter;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	private Button button;
	
	@Override
	protected void onResume() {
		super.onResume();
		String text = ServerCommunication.albumname;
		button.setText(text.substring(0, Math.min(text.length(), 35)));
	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
    	// remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // set FullScreen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
		setContentView(R.layout.ac_image_grid);
		button = (Button) findViewById(R.id.buttonalbums);
		
		//Bundle bundle = getIntent().getExtras();
		//imageUrls = bundle.getStringArray(Extra.IMAGES);

		final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
		final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
		@SuppressWarnings("deprecation")
		Cursor imagecursor = managedQuery(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
				null, orderBy + " DESC");
		
		this.imageUrls = new ArrayList<String>();
		
		for (int i = 0; i < imagecursor.getCount(); i++) {
			imagecursor.moveToPosition(i);
			int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
			imageUrls.add(imagecursor.getString(dataColumnIndex));
			
			//System.out.println("=====> Array path => "+imageUrls.get(i));
		}
		
		
		options = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.stub_image)
			.showImageForEmptyUri(R.drawable.image_for_empty_url)
			.cacheInMemory()
			.cacheOnDisc()
			.build();

		imageAdapter = new ImageAdapter(this, imageUrls);
		
		GridView gridView = (GridView) findViewById(R.id.gridview);
		gridView.setAdapter(imageAdapter);
		/*gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				startImageGalleryActivity(position);
			}
		});*/
		
		String albumtitle = getIntent().getStringExtra("albumtitle");
		int topicid = getIntent().getIntExtra("topicid",0);
		
		if(albumtitle == null) {
			ServerCommunication.albumname = getString(R.string.image_slect_album);
		}
		else {
			ServerCommunication.albumname = albumtitle;
			ServerCommunication.topicid = topicid;
		}
	}
	
    

	@TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
    	super.onWindowFocusChanged(hasFocus);
    	if(Build.VERSION.SDK_INT >= 19){
	        if (hasFocus) {
				View mDecorView = getWindow().getDecorView();
				mDecorView.setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_STABLE
					| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
					| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
					| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
					| View.SYSTEM_UI_FLAG_FULLSCREEN
					| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
			}
    	}
    }
    
	@Override
	protected void onStop() {
		imageLoader.stop();
		super.onStop();
	}

	@Override
	protected void onPause() {
		if(ServerCommunication.topicid == 0) {
			ServerCommunication.albumname = getString(R.string.image_slect_album);
			ServerCommunication.albumid = 0;
		}
		super.onPause();
	}
	
	public void btnChoosePhotosClick(View v){
		
		ArrayList<String> selectedItems = imageAdapter.getCheckedItems();
		
		if (ServerCommunication.albumid == 0 && ServerCommunication.topicid == 0) {
			Toast.makeText(this, getString(R.string.image_upload_select_album), Toast.LENGTH_SHORT).show();
		}
		else if(!(selectedItems.size() > 0)) {
			Toast.makeText(this, getString(R.string.image_upload_select_photos), Toast.LENGTH_SHORT).show();
		}
		else {
			PhotoDatabase photos = new PhotoDatabase(this);
			SQLiteDatabase db = photos.getWritableDatabase();
		    ContentValues values;
		    if(ServerCommunication.albumid == 0) {
				for(String path: selectedItems) {
					values = new ContentValues();
				    values.put("album_id", ServerCommunication.topicid);
				    values.put("path", path);
				    values.put("istopicid", 1);
					db.insert("photos", null, values);
				}
		    }
		    else {
				for(String path: selectedItems) {
					values = new ContentValues();
				    values.put("album_id", ServerCommunication.albumid);
				    values.put("path", path);
					db.insert("photos", null, values);
				}
		    }
			db.close();
			
			ServerCommunication.albumid = 0;
			ServerCommunication.topicid = 0;
			
	    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
	    	if(sharedPref.getBoolean("upload_in_wifi_only", true) && !WifiChangeBroadcastReceiver.checkWifiConnected(this)) {
	    		Toast.makeText(this, String.format(getString(R.string.image_upload_no_wifi_description),selectedItems.size()), Toast.LENGTH_LONG).show();
	    	}
	    	else {
				Toast.makeText(this, String.format(getString(R.string.image_upload_description),selectedItems.size()), Toast.LENGTH_LONG).show();
				Intent Serviceintent = new Intent(this, UploadService.class);
				startService(Serviceintent);
	    	}
			finish();
		}
	}
	
	public void chooseCategory(View v){
		Intent i = new Intent();
		i.setClass(this, ShowAlbumsActivity.class);
		startActivity(i);
	}
	
	
	
	/*private void startImageGalleryActivity(int position) {
		Intent intent = new Intent(this, ImagePagerActivity.class);
		intent.putExtra(Extra.IMAGES, imageUrls);
		intent.putExtra(Extra.IMAGE_POSITION, position);
		startActivity(intent);
	}*/

	public class ImageAdapter extends BaseAdapter {
		
		ArrayList<String> mList;
		LayoutInflater mInflater;
		Context mContext;
		SparseBooleanArray mSparseBooleanArray;
		
		public ImageAdapter(Context context, ArrayList<String> imageList) {
			mContext = context;
			mInflater = LayoutInflater.from(mContext);
			mSparseBooleanArray = new SparseBooleanArray();
			mList = new ArrayList<String>();
			this.mList = imageList;

		}
		
		public ArrayList<String> getCheckedItems() {
			ArrayList<String> mTempArry = new ArrayList<String>();

			for(int i=0;i<mList.size();i++) {
				if(mSparseBooleanArray.get(i)) {
					mTempArry.add(mList.get(i));
				}
			}

			return mTempArry;
		}
		
		public int getCount() {
			return imageUrls.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			
			if(convertView == null) {
				convertView = mInflater.inflate(R.layout.row_multiphoto_item, null);
			}

			CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
			final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
			
			imageLoader.displayImage("file://"+imageUrls.get(position), imageView, options, new SimpleImageLoadingListener() {
				@Override
				public void onLoadingComplete(Bitmap loadedImage) {
					Animation anim = AnimationUtils.loadAnimation(MultiPhotoSelectActivity.this, R.anim.fade_in);
					imageView.setAnimation(anim);
					anim.start();
				}
			});
			
			mCheckBox.setTag(position);
			mCheckBox.setChecked(mSparseBooleanArray.get(position));
			mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
			
			return convertView;
		}
		
		OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
			}
		};
	}
	
	
}